package guest

import (
	"OrgManager/app/service"
	"OrgManager/library/response"
	"OrgManager/library/util"
	"database/sql"
	"fmt"
	"github.com/gogf/gf/container/gset"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

type MemberController struct {
}

func init() {
	var c = &MemberController{} // 用户模块 路由注册 - 使用执行对象注册方式
	group := g.Server().Group("/guest/member")
	group.ALL("/login.bu", c.MemberLogin)   // 员工登录
	group.ALL("/logout.bu", c.MemberLogout) // 员工注销登录
}

// 注销
func (c *MemberController) MemberLogout(r *ghttp.Request) {
	r.Session.Remove(service.SESSION_KEY_MEMBER)
	response.Json(r, 1, "登出成功", nil)
}

// 员工登录
func (c *MemberController) MemberLogin(r *ghttp.Request) {
	data, _ := r.GetJson()
	phone := data.GetString("phone")
	password := util.Md5ToMemberPassword(data.GetString("password"))
	result, err := g.DB().Table("sys_organ").Where("status > 0 and type = ? and phone = ? and password = ? ", service.SYS_ORGAN_TYPE_MEMBER, phone, password).One()

	if err == nil {
		// 登录成功

		orgMember := result.ToMap()

		// 获取权限列表
		set := gset.New(true) // 装在权限编号
		sqlString := fmt.Sprintf("status > 0 and id in (%s)", result.ToMap()["roles"])
		roles, err := g.DB().Table("sys_role").Where(sqlString).All()
		if err == nil {
			for _, roleItem := range roles {
				values := util.StringToIntArray(roleItem["power_list"].String(), ",")
				for _, v := range values {
					set.Add(v)
				}
			}
			orgMember["power_list"] = set.String()
		} else if err == sql.ErrNoRows {
			orgMember["power_list"] = set.String()
		} else {
			glog.Error("出错了： %v \r\n", err)
			orgMember["power_list"] = set.String()
		}

		// 获取权限所属部门
		officeIdList := make([]int, 0)
		officeAll, err := g.DB().Table("sys_organ").Where("status = 1 and type = ?", service.SYS_ORGAN_TYPE_OFFICE).All()
		if err == nil {
			if gconv.Int(orgMember["roles_scope"]) == service.SYS_ORGAN_ROLES_SCOPE_OFFICE {
				officeIdList = *downAddOfficeId(&officeIdList, gconv.Int(orgMember["pid"]), officeAll)
			} else if gconv.Int(orgMember["roles_scope"]) == service.SYS_ORGAN_ROLES_SCOPE_COMPANY {
				for _, item := range officeAll {
					officeIdList = append(officeIdList, item["id"].Int())
				}
			} else {
				officeIdList = util.StringToIntArray(gconv.String(orgMember["roles_office_list"]), ",")
			}
		}
		orgMember["office_list"] = officeIdList


		glog.Infof("xxxxxxx 权限所属部门： %v \r\n", officeIdList)
		glog.Infof("xxxxxxx 登录信息： %v \r\n", orgMember )

		err = r.Session.Set(service.SESSION_KEY_MEMBER, orgMember)
		if err == nil {

			response.Json(r, 1, "登录成功", nil)
		} else {
			glog.Errorf("保存登录信息错误:%v \r\n", err)
			response.Json(r, -1, "系统忙，请稍后再试！", err)
		}

	} else if err == sql.ErrNoRows {
		// 登录失败
		response.Json(r, 0, "用户名或密码错误！", nil)
	} else {
		// 出错了
		response.Json(r, -1, "系统忙，请稍后再试！", err)
	}
}

func downAddOfficeId(list *[]int, pid int, result []gdb.Record) *[]int {
	*list = append(*list, pid)
	for _, item := range result {
		if item["pid"].Int() == pid {
			list = downAddOfficeId(list, item["id"].Int(), result)
		}
	}
	return list
}
